package org.example.promptword.controller;

import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import org.example.promptword.Vo.TagVO;
import org.example.promptword.Vo.TemplateVO;
import org.example.promptword.common.BusinessException;
import org.example.promptword.common.ResponseInfo;
import org.example.promptword.dto.TemplateCreateRequest;
import org.example.promptword.dto.TemplateQueryRequest;
import org.example.promptword.service.impl.PromptTemplateSquareServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/prompt")
public class PromptTemplateSquareController {

    @Autowired
    private PromptTemplateSquareServiceImpl promptTemplateSquareService;

    @PostMapping("/templates")
    public ResponseInfo<PageInfo<TemplateVO>> getTemplates(@RequestBody TemplateQueryRequest request) {
        try {
            PageInfo<TemplateVO> pageInfo = promptTemplateSquareService.getTemplates(request);
            return ResponseInfo.success(pageInfo);
        } catch (Exception e) {
            log.error("获取提示词模板列表失败", e);
            return ResponseInfo.fail("500", "获取提示词模板列表失败");
        }
    }

    @GetMapping("/tags")
    public ResponseInfo<List<TagVO>> getTags(@RequestParam(required = false) String name) {
        try {
            List<TagVO> tags = promptTemplateSquareService.getTags(name);
            return ResponseInfo.success(tags);
        } catch (Exception e) {
            log.error("获取标签列表失败", e);
            return ResponseInfo.fail("500", "获取标签列表失败");
        }
    }

    /**
     * 插入模板
     */
    @PostMapping("/template/add")
    public ResponseInfo<Integer> createTemplate(@RequestBody TemplateCreateRequest request) {
        try {
            Integer templateId = promptTemplateSquareService.createTemplate(request);
            return ResponseInfo.success(templateId);
        } catch (BusinessException e) {
            log.warn("创建提示词模板失败: {}", e.getMessage());
            return ResponseInfo.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("创建提示词模板发生系统错误", e);
            return ResponseInfo.fail("500", "系统错误，请稍后重试");
        }
    }

}
